package com.example.crm.web.controller;

import com.example.crm.entity.Role;
import com.example.crm.entity.User;
import com.example.crm.service.IRoleService;
import com.example.crm.service.IUserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lenovo
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;

    /**
     * 用户列表
     */
    @RequestMapping("/list")
    public String list(Model model, @RequestParam(required = false) String usrName,
                       @RequestParam(required = false, defaultValue = "0") Long roleId,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex) {
        Sort sort = Sort.by(Sort.Direction.ASC, "usrId");
        //控制分页的辅助类，可以设置页码(从0开始！！！)、每页的数据条数、排序等
        Pageable pageable = PageRequest.of(pageIndex - 1, 5, sort);
        Page<User> userPage = userService.findUsers(usrName, roleId, pageable);
        model.addAttribute("userPager", userPage);
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);
        return "user/list";
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(Model model) {
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);
        return "user/add";
    }

    /**
     * 新增和修改
     */
    @RequestMapping("/save")
    public String save(User user) {
        userService.saveUser(user);
        return "redirect:/user/list";
    }

    /**
     * 修改页面
     */
    @RequestMapping("/edit")
    public String edit(Long usrId, Model model) {
        User user = userService.getUser(usrId);
        List<Role> list = roleService.findAllRoles();
        model.addAttribute("user", user);
        model.addAttribute("roles", list);
        return "user/edit";
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping("/del")
    public Map del(Long usrId) {
        Map map = new HashMap();
        userService.deleteUser(usrId);
        map.put("delResult", "true");
        return map;
    }
}